<?php

/**
 * Reverse bidding system Users Class
 *
 * Buyer related functions are handled by this controller.
 *
 * @package        Reverse bidding system
 * @subpackage    Controllers
 * @category    Project
 * @author        Cogzidel Dev Team
 * @version        Version 1.0
 * @created        December 31 2008
 * @link        http://www.cogzidel.com
 *
 * <Reverse bidding system>
 * Copyright (C) <2009>  <Cogzidel Technologies>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 * If you want more information, please email me at bala.k@cogzidel.com or
 * contact us from http://www.cogzidel.com/contact

 */
class Users extends Controller
{

    //Global variable
    public $outputData; //Holds the output data for each view
    public $loggedInUser;

    /**
     * Constructor
     *
     * Loads language files and models needed for this controller
     */
    function Users()
    {
        parent::Controller();

        //Get Config Details From Db
        $this->config->db_config_fetch();

        //Manage site Status
        if ($this->config->item('site_status') == 1)
            redirect('offline');

        //Debug Tool
        //$this->output->enable_profiler=true;

        //Load Models Common to all the functions in this controller
        $this->load->model('common_model');
        $this->load->model('auth_model');
        $this->load->model('skills_model');
        $this->load->model('user_model');

        //Page Title and Meta Tags
        $this->outputData = $this->common_model->getPageTitleAndMetaData();

        //Get Logged In user
        $this->loggedInUser = $this->common_model->getLoggedInUser();

        $this->outputData['loggedInUser'] = $this->loggedInUser;

        //Get Footer content
        $conditions = array('page.is_active' => 1);
        $this->outputData['pages'] = $this->page_model->getPages($conditions);

        //Get Latest Projects
        $limit_latest = $this->config->item('latest_projects_limit');
        $limit3 = array($limit_latest);
        $this->outputData['latestProjects'] = $this->skills_model->getLatestProjects($limit3);

        //language file
        $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/programmerConfirm', $this->config->item('language_code'));
    } //Controller End
    // --------------------------------------------------------------------

    /**
     * Loads Home page of the site.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function login()
    {
        //language file
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        //Load Models - for this function
        $this->load->model('user_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load cookie
        $this->load->helper('cookie');

        //Load Alert Helper
        $this->load->helper('alert');

        //Load Form Helper
        $this->load->helper('form');

        //Load Library File
        $this->load->library('encrypt');

        if($this->session->userdata('user_id')){
            redirect('home');
        }


		$userGG = $this->session->userdata('userGG');
		if($userGG != FALSE){
			$this->outputData['userGG'] = $userGG;
			$this->session->unset_userdata('userGG');
		}

        // check the login for remember user
        if ($this->auth_model->getUserCookie('user_name') != '' and $this->auth_model->getUserCookie('user_password') != '') {
            $conditions = array('user_name' => $this->auth_model->getUserCookie('user_name'), 'password' => md5($this->auth_model->getUserCookie('user_password')), 'users.user_status' => '1');
            $query = $this->user_model->getUsers($conditions);
            if ($query->num_rows() > 0) {
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success',$this->lang->line('Login successful')));

            }
            redirect('buyer/viewMyProjects');
        }

        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
        //pr($_POST);
        //Get Form Data
        if ($this->input->post('usersLogin')) {
            //Set rules
            $this->form_validation->set_rules('username', 'lang:user_name_validation', 'required|trim|min_length[5]|xss_clean');
            $this->form_validation->set_rules('password', 'lang:password_validation', 'required|ming_length[5]|trim|xss_clean');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
            $this->form_validation->set_message('valid_email', '%s ' . $this->lang->line('valid_email'));

            if ($this->form_validation->run()) {
                if (getBanStatus($this->input->post('username'))) {
                    $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Ban Error')));
                    redirect('users/login');
                }


                // Puhal Changes Removed the role Id from the conditions, inorder to remove the buyer and programmer radio button (Sep 17 Issue 4)
                $conditions = array('user_name' => $this->input->post('username'), 'password' => md5($this->input->post('password')), 'users.user_status' => '1');
                $query = $this->user_model->getUsers($conditions);


                if ($query->num_rows() > 0) {
                    $row = $query->row();
                    // update the last activity in the users table
                    $updateData = array();
                    $updateData['last_activity'] = get_est_time();
                    //Get Activation Key
                    $activation_key = $row->id;
                    // update process for users table
                    $this->user_model->updateUser(array('id' => $row->id), $updateData);

                    //Check For Password
                    //if($this->input->post('pwd')==$this->common_model->getDecryptedString($row->password))
                    if (1) {
                        //Set Session For User
                        $this->auth_model->setUserSession($row);
                        // Puhal Changes for the Remember me button (Sep 17 Issue 3)
                        if ($this->input->post('remember')) {
                            $insertData = array();
                            $insertData['username'] = $this->input->post('username');
                            $insertData['password'] = $this->input->post('password');
                            $expire = 60 * 60 * 24 * 100;
                            if ($this->auth_model->getUserCookie('uname') == '') {
                                $this->user_model->addRemerberme($insertData, $expire);
                            }
                        } else {
                            $this->user_model->removeRemeberme();
                        }
                        //Notification message
                        //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Login successful')));
                        redirect('buyer/editProfileUpdate');
                        if ($this->session->userdata('job_id') != '') {
                            $jobid = $this->session->userdata('job_id');
                            $this->session->unset_userdata('job');
                            $this->session->unset_userdata('view');
                            $this->session->unset_userdata('job_id');
                            redirect('project/view/' . $jobid);
                        }
                        // check for private project user login
                    } else {

                        //Notification message
                        $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Incorrect username or password')));
                        redirect('users/login');
                    }

                } else {

                    //Notification message
                    $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Incorrect username or password')));
                    redirect('users/login');
                } //If username exists
            }
            //If End - Check For Validation
        } //If End - Check For Form Submission
        $this->load->view('users/loginUsers', $this->outputData);
    } //Function login End

    // --------------------------------------------------------------------


    function loginUpdate(){
        //language file
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        //Load Models - for this function
        $this->load->model('user_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load cookie
        $this->load->helper('cookie');

        //Load Alert Helper
        $this->load->helper('alert');

        //Load Form Helper
        $this->load->helper('form');

        //Load Library File
        $this->load->library('encrypt');

        if($this->session->userdata('user_id')){
            redirect('home');
        }

        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
        //Set rules
        $this->form_validation->set_rules('inputfield', 'lang:user_name_validation', 'required|trim|min_length[5]|xss_clean');
        $this->form_validation->set_rules('login-password', 'lang:password_validation', 'required|ming_length[5]|trim|xss_clean');

        $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
        $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
        //$this->form_validation->set_message('valid_email', '%s ' . $this->lang->line('valid_email'));
        if ($this->form_validation->run()) {          
            $input_login = $this->input->post('inputfield',TRUE);
            $password_login = md5($this->input->post('login-password',TRUE));
            $query = $this->user_model->getUsersInputField($input_login,$password_login);
            if ($query->num_rows() > 0){
                $row = $query->row();

                //update the last activity in the users table
                $updateData = array();
                $updateData['last_activity'] = get_est_time();
                //Get Activation Key
                $activation_key = $row->id;
                // update process for users table
                $this->user_model->updateUser(array('id' => $row->id), $updateData);
                if (1) {
                    //Set Session For User
                    $this->auth_model->setUserSession($row);
                    //print_r($this->session->all_userdata());exit;
                    
                    // kiểm tra nếu check vào nút remember me
                    if($this->input->post('login-checkbox',TRUE)){
                        //print_r("check remember");exit;
                        $insertData = array();
                        $insertData['inputField'] = $this->input->post('inputfield');
                        $insertData['password'] = $this->input->post('login-password');
                        $expire = 60 * 60 * 24 * 100;
                        //if ($this->auth_model->getUserCookie('inputfield') == '') {
                            $this->user_model->addRemerberme($insertData, $expire);
                        //}
                    }else {
                        $this->user_model->removeRemeberme();
                    }
					// add project wishlist
                    if($this->input->post('project_id')){
                        $redirect_url = $this->input->post('redirect_url');
                        $this->load->model("project_wishlist_model");
                        $dataInsert = array(
                            'user_id' => $this->session->userdata('user_id'),
                            'project_id' => $this->input->post('project_id'),
                            'created' => time()
                        );
                        $this->project_wishlist_model->insertProjectWishlist($dataInsert);

                        echo json_encode(array(
                            "status"    => "success",
                            "msg"       => "joblist",
                            "redirect_url" => $redirect_url
                        ));exit;
                    }

                    if($this->input->post('dev_id')){
                        $condition_watchlist = array('user_watchlist.user_id'=>$this->session->userdata('user_id'),'user_watchlist.dev_id' => $this->input->post('dev_id'));
                        $fields_watchlist = array('user_watchlist.user_id');
                        $result_watchlist = $this->user_model->getWatchList($condition_watchlist,$fields_watchlist);

                        if($result_watchlist->num_rows() == 0 ) {
                            $dataInsert = array(
                                'user_id' => $this->session->userdata('user_id'),
                                'dev_id' => $this->input->post('dev_id'),
                                'created' => time()
                            );
                            $this->user_model->addWatchList($dataInsert);
                        }
                        echo json_encode(array(
                            "status"    => "success",
                            "msg"       => "devlist",
                        ));exit;
                    }

                    if($this->input->post('redirect_url_invite',TRUE)){
                        $url = $this->input->post('redirect_url_invite',TRUE);
                        echo json_encode(array(
                            "status"    => "success",
                            "msg"       => "invite-freelancer",
                            "invite_freelancer_url" => $url
                        ));exit;
                    }

                    if($this->session->userdata('role') == 'programmer'){
                        // chuyển đến dashboard của developer
                        //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('login_success')));
                        echo json_encode(array(
                            "status"    => "success",
                            "msg"       => "programmer"
                        ));exit;
                        //redirect('programmer/viewMyProjects');


                    }else{
                        // chuyển đến dashboard của buyer
                        //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('login_success')));

                        echo json_encode(array(
                            "status"    => "success",
                            "msg"       => "buyer"
                        ));exit;
                        //redirect('buyer/viewMyProjects');



                    }
                }
            }else{
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('login_failed')));
               // print_r("abf");exit;
                echo json_encode(array(
                                    "status"    => "error",
                                    "msg"       => ""
                                ));exit;

            }

        }
    }

    /*function loginUpdate(){
        //language file
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        //Load Models - for this function
        $this->load->model('user_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load cookie
        $this->load->helper('cookie');

        //Load Alert Helper
        $this->load->helper('alert');

        //Load Form Helper
        $this->load->helper('form');

        //Load Library File
        $this->load->library('encrypt');

        if($this->session->userdata('user_id')){
            redirect('home');
        }

        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
        //Set rules
        $this->form_validation->set_rules('inputfield', 'lang:user_name_validation', 'valid_email|required|trim|min_length[5]|xss_clean');
        $this->form_validation->set_rules('login-password', 'lang:password_validation', 'required|ming_length[5]|trim|xss_clean');

        $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
        $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
        if($this->form_validation->run() == TRUE){
            $error = array();
            // input-field nhập vào là email - kiểm tra email trong hệ thống
            $email = $this->input->post('inputfield',TRUE);
            $password = md5($this->input->post('login-password',TRUE));
            $checkEmail = $this->user_model->checkEmailExists($email);
            if($checkEmail->num_rows() == 0){
                $error['status_email']    = 'email-not-exists';
                $error['msg_email']       = 'Email không tồn tại trong hệ thống';
            }
            else{
            // kiểm tra password
                $condition = array('users.email' => $email,'users.password' => $password);
                $checkPass = $this->user_model->checkEmailPassIsExists($condition);
                if($checkPass->num_rows() == 0){
                    $error['status_pass']    = 'pass-not-exists';
                    $error['msg_pass']       = 'Password không tồn tại trong hệ thống';
                }
            }

            echo json_encode($error);
        }else{
            $error = array();
            $username = $this->input->post('inputfield',TRUE);
            $password = md5($this->input->post('login-password',TRUE));
            $checkUsername = $this->user_model->checkUsernameExists($username);
            if($checkUsername->num_rows() == 0){
                $error['status_user']    = 'user-not-exists';
                $error['msg_user']       = 'Username không tồn tại trong hệ thống';
            }
            else{
            // kiểm tra password
                $condition = array('users.user_name' => $username,'users.password' => $password);
                $checkPass = $this->user_model->checkEmailPassIsExists($condition);
                if($checkPass->num_rows() == 0){
                    $error['status_pass']    = 'pass-not-exists';
                    $error['msg_pass']       = 'Password không tồn tại trong hệ thống';
                }
            }
            echo json_encode($error);
            // input-field nhập vào là username
        }
    }// end function*/

    function checkUserInputField(){
        //load validation libraray
        $this->load->library('form_validation');
        $this->form_validation->set_rules('inputfield', 'lang:email', 'trim|required|valid_email|min_length[5]|max_length[50]|xss_clean');
        // kiểm tra input field là email hoặc username
        $inputField = $this->input->post("inputfield",TRUE);
        if ($this->form_validation->run() == TRUE) {
            // input field là email
            $result = $this->user_model->checkEmailExists($inputField);
            if(count($result->row_array()) == 0){
                echo "false";
            }else{
                echo "true";
            }
        }else{
            // input field là username
            $result = $this->user_model->checkUsernameExists($inputField);
            if(count($result->row_array()) == 0){
                echo "false";
            }else{
                echo "true";
            }
        }
    }


    function checkUserPasswordField(){
        //load validation libraray
        $this->load->library('form_validation');
        $this->form_validation->set_rules('inputfield', 'lang:email', 'trim|required|valid_email|min_length[5]|max_length[50]|xss_clean');
        // kiểm tra input field là email hoặc username
        $inputField = $this->input->post("inputfield",TRUE);
        if ($this->form_validation->run() == TRUE) {
            // input field là email
            $result = $this->user_model->checkEmailExists($inputField);
            if(count($result->row_array()) == 0){
                echo "false";
            }else{
                // có input field kiểm tra password
            }
        }else{
            // input field là username
            $result = $this->user_model->checkUsernameExists($inputField);
            if(count($result->row_array()) == 0){
                echo "false";
            }else{
                echo "true";
            }
        }
    }

    /**
     * Loads forgotPassword page of the site.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function forgotPassword()
    {
        //language file
        $this->lang->load('enduser/forgotPassword', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));

        //Load Models - for this function
        $this->load->model('user_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        //Get Form Data	- Forgot Password
        if ($this->input->post('forgotPassword')) {
            //Set rules
            $this->form_validation->set_rules('email_fp', 'lang:user_name_validation', 'required|valid_email|trim|min_length[5]|xss_clean');
            if ($this->form_validation->run()) {
                $email = $this->input->post('email_fp');
                $conditions = array('email' => $email);
                $query = $this->user_model->getUsers($conditions);
                $usersData = $query->row();
                // echo "<pre>";
                // print_r($usersData);
                // echo "</pre>";exit;
                if ($query->num_rows() > 0) {
                    // echo "<pre>";
                    // print_r($usersData);
                    // echo "</pre>";exit;
                    //Send Mail
                    $conditionUserMail = array('email_templates.type' => 'forget_password');
                    $this->load->model('email_model');
                    $result = $this->email_model->getEmailSettings($conditionUserMail);
                    $rowUserMailContent = $result->row();
                    // tạo biến random và update vào csdl
                    $rand_temp = md5(uniqid(rand(),TRUE));
                    // update vào csdl
                    $conditionUpdate = array("users.email" => $email);
                    $updateData = array("users.key_rand" => $rand_temp);
                    $this->user_model->updateKeyRand($conditionUpdate,$updateData);
                    $splVars = array(
                        "!site_title" => $this->config->item('site_title'), 
                        "!url" => site_url(''), 
                        "!link" => site_url('users/resetPassword/'.$rand_temp),
                    );

                    $mailSubject = $rowUserMailContent->mail_subject;
                    $mailContent = strtr($rowUserMailContent->mail_body, $splVars);
                    // echo "<pre>";
                    // print_r($mailContent);
                    // echo "</pre>";exit;
                    $toEmail = $usersData->email;
                    $fromEmail = $this->config->item('site_admin_mail');
                    // echo $fromEmail." | ".$toEmail."<br />";
                    // echo "subject : ".$mailSubject." | content".$mailContent;
                    // exit;
                    $result_send = $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                    if($result_send){
                        //Notification message
                        $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', 'Your password has been sent to your registered email address!'));
                    }else{
                        //Notification message
                        $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'Send Email failed'));
                    }
                    redirect('users/notice');
                } else {
                    //Notification message
                    $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'Email Failed'));
                    redirect('users/forgotPassword');
                }
            }
            //If End - Check For Validation
        } //If End - Check For Form Submission For Forgot Password

        
        $this->load->view('users/forgotPassword', $this->outputData);
    } //Function forgotPassword End
    // --------------------------------------------------------------------


    function resetPassword(){
       $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
       $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        if($this->uri->segment(3,'0')){
            $key = $this->uri->segment(3,'0');
            //kiểm tra key_rand trong csdl
            $kq = $this->user_model->checkKeyRand($key);
            if($kq->num_rows() > 0){
                // có tồn tại key_rand trong csdl
                $this->outputData['id'] = $kq->row()->id;
                // update password mới vào csdl
                if($this->input->post('btn-reset-pwd',TRUE)){
                    $pwd = md5($this->input->post('pwd-new',TRUE));
                    //echo $pwd." || ".$this->outputData['id'];
                    $condition = array(
                        "users.id" => $this->outputData['id']
                    );
                    $updateData = array(
                        "users.password" => $pwd,
                        "users.key_rand" => ''
                    );
                    $result = $this->user_model->updatePassword($condition,$updateData);
                    $query = $this->user_model->getUsersInputField($kq->row()->email,$pwd);
                    if($query->num_rows() > 0){
                        // lưu session
                        $this->auth_model->setUserSession($query->row());
                        
                        if($this->session->userdata('role') == 'programmer'){
                            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('change_pass_success')));
                            // chuyển đến dashboard của developer
                            redirect('programmer/viewMyProjects');
                        }else{
                            // chuyển đến dashboard của buyer
                            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('change_pass_success')));
                            redirect('buyer/viewMyProjects');
                        }
                    }
                    
                }                
            }else{
                // không tồn tại key_rand trong csdl - hoặc do đã reset pass nên đã xóa đi
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'This link in valid.'));
                redirect("users/forgotPassword");
            }


        }

        $this->load->view("users/resetPasswordForm",$this->outputData);
    }

    function active_mail_register(){
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        if($this->uri->segment(3,'0')){
            $key = $this->uri->segment(3,'0');
            //kiểm tra key_rand trong csdl
            $kq = $this->user_model->checkActiveEmail($key);
            if($kq->num_rows() > 0){
                // update active_email field == 1
                $condition = array(
                        "users.id" => $kq->row()->id,
                );
                $updateData = array(
                    "users.active_email" => 1
                );
                $result = $this->user_model->updatePassword($condition,$updateData);
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', 'Your email is actived'));
                redirect('users/login');
            }else{
                // don't nothing
            }

        }

    }

    /**
     * Loads logout .
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function logout()
    {
        //Load login Users
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));

        $this->auth_model->clearUserSession();
        //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Logout successful')));
        $this->auth_model->clearUserCookie(array('username', 'password'));
        $this->auth_model->clearUserCookie(array('user_name', 'user_password'));
        redirect('home');

    } //Function logout End

    // --------------------------------------------------------------------

    /**
     * Loads login for user to post  .
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function post()
    {
        $this->auth_model->clearUserSession();
        $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('logout_success')));
        redirect('info');
    } //Function logout End

    /**
     *Get the  job deatils for session check
     *
     * @access    public
     * @param    nil
     * @return    void
     */

    function getData()
    {
        //language file
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));

        //Load Models - for this function
        $this->load->model('user_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load cookie
        $this->load->helper('cookie');

        //Load Form Helper
        $this->load->helper('form');

        //Load Library File
        $this->load->library('encrypt');
        $this->uri->segment(4);

        if ($this->uri->segment(3) != '') {

            $this->session->set_userdata('project', 'project');
            $this->session->set_userdata('view', 'view');
            $this->session->set_userdata('id', $this->uri->segment(3, 0));


        }
        redirect('users/login');
    }//Function getData End
    //---------------------------------------------------------------------------------

    /**
     * get the details from private project to store session
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function getProjectDetails()
    {
        //language file
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));

        //Load Models - for this function
        $this->load->model('user_model');


        //load validation libraray
        $this->load->library('form_validation');

        //Load cookie
        $this->load->helper('cookie');

        //Load Form Helper
        $this->load->helper('form');

        //Load Library File
        $this->load->library('encrypt');
        $this->uri->segment(4);

        if ($this->uri->segment(3) != '') {

            $this->session->set_userdata('private', 'project');
            $this->session->set_userdata('type', 'view');
            $this->session->set_userdata('project_id', $this->uri->segment(3, 0));
            $this->session->set_userdata('private_user', $this->uri->segment(4, 0));
            $this->session->set_userdata('creator_id', $this->uri->segment(5, 0));
            $condition = 'projects.id=' . $this->uri->segment(3, 0);
            $query = "SELECT * FROM projects WHERE " . $condition;
            $result = $this->db->query($query);
            foreach ($result->result() as $project) {
                $project_name = $project->project_name;
            }
            redirect('users/login/' . $project_name);
        }

    }//Function getProjectDetails End
    //----------------------------------------------------------------------------


    //----------------------------------------------------------------------------
    /**
     * get the details from private project to store session
     *
     * @access    public
     * @param    nil
     * @return    void
     */ 
    function addUserSkill(){
        $this->load->view("buyer/addUserSkill");
    }
    //----------------------------------------------------------------------------


    //----------------------------------------------------------------------------
    /**
     * get the details from private project to store session
     *
     * @access    public
     * @param    nil
     * @return    void
     */ 
    function do_addUserSkill(){
       $this->load->model('user_model');
       $skill_string = $this->input->post('skill');
       if($skill_string != ""){
         $condition = array("user_id"=>$this->session->userdata('user_id'));
           $field = array("user_categories"=>$skill_string);
           $temp = $this->user_model->addSkillInDB($condition,$field);
           if($temp){
            echo json_encode(array("data"=>"ok","msg"=>true));      
           }else{
            echo json_encode(array("data"=>"not ok","msg"=>false));        
           }
       }else{
            echo json_encode(array("data"=>"Please fill the input","msg"=>false));        
       }      
    }


    function updateSkill(){
         $this->load->model('user_model');
         $user_id = $this->session->userdata('user_id');
         $user_info = array("user_categories"=>$this->user_model->getUserSkill($user_id));
         $this->outputData['user_info'] = $user_info['user_categories'];
         $this->load->view("buyer/updateSkill",$this->outputData);
    }

    function reloadUsername(){
        $this->load->model('user_model');
        $user_id = $this->session->userdata('user_id');
        $data = $this->user_model->getSingleUsername($user_id);
        $this->outputData['user_info'] = $data;
        $this->load->view("buyer/reloadUsername",$this->outputData);
    }

    function delUserSkill(){
        $name_skill = $this->input->post("name_skill");
        $user_id = $this->session->userdata('user_id');
        $result = $this->user_model->deleteUserSkill($user_id,$name_skill);
        echo json_encode(array("data"=>"Delete success","msg"=>true));      
    }


    function updateUsername(){
        $this->load->model('user_model');
        $username = $this->input->post("username");
        if($username != ''){
            $user_id = $user_id = $this->session->userdata('user_id');
            $condition = array("id"=>$user_id);
            $updateData = array("user_name"=>$username);
            $result = $this->user_model->update_username($condition,$updateData);
            if($result){
                echo json_encode(array("data"=>"Update success.","msg"=>true));
            }else{
                echo json_encode(array("data"=>"Update unsuccess","msg"=>false));
            }
        }else{
            echo json_encode(array("data"=>"Please fill the input","msg"=>false));
        }
        
    }

    function updateLocation(){
        $this->load->model('user_model');
        $location = $this->input->post("location");
        if($location != ''){
            $user_id = $user_id = $this->session->userdata('user_id');
            $condition = array("id"=>$user_id);
            $updateData = array("city"=>$location);
            $result = $this->user_model->update_location($condition,$updateData);
            if($result){
                echo json_encode(array("data"=>"Update success.","msg"=>true));
            }else{
                echo json_encode(array("data"=>"Update unsuccess","msg"=>false));
            }
        }else{
            echo json_encode(array("data"=>"Please fill the input","msg"=>false));
        }
    }

    function reloadLocation(){
        $this->load->model('user_model');
        $user_id = $this->session->userdata('user_id');
        $data = $this->user_model->getSingleLocation($user_id);
        $this->outputData['user_info'] = $data;
        $this->load->view("buyer/reloadLocation",$this->outputData);
    }

    function updateDescription(){
        $this->load->model('user_model');
        $description = $this->input->post("description");
        if($description !=''){
            $user_id = $user_id = $this->session->userdata('user_id');
            $condition = array("id"=>$user_id);
            $updateData = array("profile_desc"=>$description);
            $result = $this->user_model->update_desciprion($condition,$updateData);
            if($result){
                echo json_encode(array("data"=>"Update success.","msg"=>true));
            }else{
                echo json_encode(array("data"=>"Update unsuccess","msg"=>false));
            }
        }else{
            echo json_encode(array("data"=>"Please fill the input","msg"=>false));
        }
    }

    function reloadDescription(){
        $this->load->model('user_model');
        $user_id = $this->session->userdata('user_id');
        $data = $this->user_model->getSingleDescription($user_id);
        $this->outputData['user_info'] = $data;
        $this->load->view("buyer/reloadDescription",$this->outputData);
    }

    


    //----------------------------------------------------------------------------
    function findFreelancer(){
        $this->load->model("user_model");
        $this->load->model("skills_model");
        //if($this->session->userdata('user_id')){
        $this->load->library('pagination');

        $this->load->helper('file');
        $this->load->helper('users');
        $this->load->helper('projectcases');

        $conditions = array('groups.is_deleted' => 0);
        $fields = array('groups.group_name','groups.id','groups.parent_id');
        $listCategories = $this->skills_model->getGroup($conditions,$fields);

        foreach($listCategories->result() as $item){
            if($item->parent_id == 0) {
                $this->outputData['listParentCategories'][$item->id]['id'] = $item->id;
                $this->outputData['listParentCategories'][$item->id]['name'] = $item->group_name;
            }
        }

        foreach($this->outputData['listParentCategories'] as $item){
            foreach($listCategories->result() as $item2){
                if($item['id'] == $item2->parent_id){
                    $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['id'] = $item2->id;
                    $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['name'] = $item2->group_name;
                    $numUserCategories = $this->user_model->getCountCategorybyUser($item2->id);
                    if($numUserCategories->num_rows() > 0)
                        $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['num'] = $numUserCategories->num_rows();
                    else
                        $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['num'] = 0;
                }
            }
        }

        $params = ($this->uri->uri_to_assoc())?$this->uri->uri_to_assoc():'';

        //print_r($params);
        if($params == "")
            $stringCategories = "";

        $condition_freelancer = array(
            "users.suspend_status"=>'0',
            "users.ban_status" => '0',
            "users.role_id" => 2 ,
        );



        $this->outputData['count'] = $this->user_model->getUsers($condition_freelancer,array('users.id'));
         //filter group child
        $parent_ids = isset($params['g'])?$params['g']:0;
        if($parent_ids != 0){
            //count($this->outputData['listParentCategories'][$parent_ids]['child']) > 0
            if(!empty($this->outputData['listParentCategories'][$parent_ids]['child'])){
                foreach($this->outputData['listParentCategories'][$parent_ids]['child'] as $item){
                    $listCategories = getCategoriesByGroup($item['id']);
                    if($listCategories){
                        foreach($listCategories->result() as $item2){
                            $stringCategories[] = $item2->id;
                        }
                    }
                }
                $stringCategories = implode(',',$stringCategories);
            }else{
                $stringCategories = array();
            }

        }


        // filter country
        $country_id = $this->input->post('country');
        if($country_id){
            $condition_freelancer['users.country_id'] = $country_id;
            $orderby = array('users.country_id','desc');
        }


        // filter group parent
        $country_id = isset($params['ct'])?$params['ct']:0;
        if($country_id != 0){
            $condition_freelancer['users.user_rating'] = $country_id;
            $orderby = array('users.user_rating','desc');
        }

        // filter group parent
        $group_id = isset($params['c'])?$params['c']:0;
        if($group_id != 0){
            $listCategories = getCategoriesByGroup($group_id);
            $stringCategories = array();
            if($listCategories){
                foreach($listCategories->result() as $item){
                    $stringCategories[] = $item->id;
                }
                $stringCategories = implode(',',$stringCategories);
            }
        }

        // filter feedback
        $feedback = isset($params['fb'])?$params['fb']:0;
        if($feedback != 0){
            $condition_freelancer['users.user_rating'] = $feedback;
            $orderby = array('users.user_rating','desc');
        }

        // filter review
        $num_reviews = isset($params['rv'])?$params['rv']:0;
        if($num_reviews != 0){
            $condition_freelancer['users.num_reviews >'] = $num_reviews;
            $orderby = array('users.num_reviews','desc');
        }

        $userId = $this->session->userdata('user_id');

        $data['page_title'] = $this->outputData['page_title'];

        $page_rows = $this->config->item('mail_limit');
        $page = isset($_GET['p'])?$_GET['p']:1;
//        if ($page > 0)
//            $page = ($page - 1) * $page_rows;

        $max = array($page_rows,($page - 1) * $page_rows);


//        echo $this->db->last_query();exit;

        $condition = array('categories.is_deleted' => 0);
        $fields = array('categories.id','categories.category_name');
        $listCategory = $this->skills_model->getCategory($condition,$fields);

        if($listCategory->num_rows() > 0){
            foreach($listCategory->result_array() as $item){
                $this->outputData['listCategory'][$item['id']] = $item['category_name'];
            }
        }

        $fields = array('users.id');

        if(isset($stringCategories) == TRUE && (count($stringCategories) > 0) ) {
            $this->outputData['countFreelancer'] = $this->user_model->getFreelancer($condition_freelancer, $userId, null, $stringCategories, $fields);
        }else{
                $this->outputData['countFreelancer'] = $this->user_model->getFreelancer($condition_freelancer, $userId, null, null, $fields);
            }
        //print_r(build_url($params));

//        if($params != "")
//            $href = build_url($params);
//        else
//            $href = "";
//
//        // pagination
//        $config['base_url']     = site_url('users/findFreelancer'.$href);
//        $config['total_rows']   = $this->outputData['countFreelancer']->num_rows();
//        $config['per_page'] = $page_rows;
//        $config['cur_page'] = $start;
//        $this->pagination->initialize($config);

        $href = current_url();
        $config['base_url'] 	= $href;
        $config['total_rows'] 	= $this->outputData['countFreelancer']->num_rows();
        $config['per_page'] = $page_rows;
        $config['cur_page'] = $page;

        $this->pagination->initialize($config);
        //$this->outputData['total_project']   = $jobs->num_rows();
        $this->outputData['pagination']   = $this->pagination->create_links(false,'job');

        if(!empty($orderby) || !isset($orderby)) {
            $orderby = array();
        }




        if(isset($stringCategories) == TRUE && (count($stringCategories) > 0))
            $this->outputData['listFreelancer'] = $this->user_model->getFreelancer($condition_freelancer,$userId,$max,$stringCategories,null,$orderby);
        else
            $this->outputData['listFreelancer'] = $this->user_model->getFreelancer($condition_freelancer,$userId,$max,null,null);

//echo $this->db->last_query();
        //print_r($this->outputData['listFreelancer']->result_array());

        // load contries
        $this->outputData['countries'] = $this->skills_model->getCountries(NULL, NULL, NULL, array('0' => 30));



        $this->outputData['params']   = $params;


        //print_r($this->outputData['listParentCategories']);exit;
        $this->load->view("freelancer/findFreelancer",$this->outputData);
//        }else{
//            $this->session->set_flashdata('flash_message',$this->common_model->flash_message("error",'You must be logged in to find Freelancer.'));
//            redirect("users/login");
//        }

    }


 //----------------------------------------------------------------------------
    /**
     * find freelancer
     *
     * @access    public
     * @param    nil
     * @return    void
     */ 

    function findFreelancer1(){
             $this->load->model("user_model");
             $this->load->model("skills_model");
            //if($this->session->userdata('user_id')){
            $this->load->library('pagination');
             
            $category_ids = $this->uri->segment(4,'');
            
            $userId = $this->session->userdata('user_id');
            $condition = array(
	            "users.suspend_status"=>'0',
	            "users.ban_status" => '0',
	            "users.role_id" => 2,
            );
            $data['page_title'] = $this->outputData['page_title'];
            $result = $this->user_model->getCountFreelancer($condition,$userId);

            $page_rows = $this->config->item('mail_limit');
            $start = $this->uri->segment(3,'0');
            if ($start > 0)
        		$start = ($start - 1) * $page_rows;
            
            $max = array($page_rows, $start);

            // pagination
            $config['base_url']     = site_url('users/findFreelancer');
            $config['total_rows']   = count($result->result_array());
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $start;
            $this->pagination->initialize($config);



            $kq = $this->user_model->getFreelancer($condition, $userId, $max, $category_ids);

            $data['data'] = $kq->result_array();
            
            $data['pagination'] = $this->pagination->create_links2(false, 'findFreelancer');

            // load groups
            $condition = array('is_active' => 1);
            $data['groupCategories'] = $this->skills_model->getGroupsWithCategory($condition);
            
            if($category_ids != ''){
            	$data['categories_selected'] = $this->skills_model->getCategories(NULL, "categories.id, categories.category_name", explode(',',$category_ids));
            	$data['category_ids'] = $category_ids;
            }
            

            $this->load->view("freelancer/findFreelancer",$data);
//        }else{
//            $this->session->set_flashdata('flash_message',$this->common_model->flash_message("error",'You must be logged in to find Freelancer.'));
//            redirect("users/login");
//        }
        
    }
 //----------------------------------------------------------------------------
    function editImageProfile(){
        //print_r($_FILES);exit;
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));



        //Load Library Validation
        $this->load->library('upload');
        $this->load->library('images');

        //Load Form Helper
        $this->load->helper('form');
        $this->load->helper('file');

        if($_FILES){
            //$this->form_validation->set_rules('image', 'lang:attachment', 'callback_check_image');
            $file = upload_image($_FILES,'logos','image',4000,5000);
            // echo "<pre>";
            // print_r($file);
            // echo "</pre>";
            // exit;
            if(isset($file['file_name']) == TRUE){
                // $optionImage = array (
                //     'upload-dir' => ROOT_PATH.'/files/logos',
                //     'thumbs' => array (
                //         array (
                //             'width' => 245,
                //             'height' => 185,
                //             'type' => 'absolute',
                //             'watermark' => false,
                //             'override' => true
                //         )) );
                // $this->images->resizeImage($file['file_name'], $optionImage);
                $updateData['logo']    = $file['file_name'];

                $updateKey = array('id' => $this->loggedInUser->id);
                $this->user_model->updateUser($updateKey, $updateData);
                $filepath = $this->config->item('basepath').'files/logos/'.$this->loggedInUser->logo;

                @unlink ($filepath);
                // print_r($updateData);exit;
                $data = array('stt'=>'success','message'=>$file);
                echo json_encode($data);exit;
            }else{
                $data = array('stt'=>'error','message'=>$file);
                echo json_encode($data);exit;
            }

        }
    } // Edit Image Profile Buyer

    function editResume(){
        // load library form_validation
        $this->load->library('form_validation');

        //load languages
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));
        $this->lang->load('enduser/editProfile',$this->config->item('language_code'));

        //Load User model
        $this->load->model('user_model');

        $this->form_validation->set_rules('resume', 'lang:Resume', 'required|xss_clean|min_length[5]');

        $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
        $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
        if($this->form_validation->run() == TRUE){
            if($this->loggedInUser->id){
                $fields = array('users.resume');
                $conditions = array('users.id'=>$this->loggedInUser->id);
                $user_resume = $this->user_model->getUsers($conditions,$fields)->row_array();

                $user_resume = unserialize($user_resume['resume']);
                //print_r($user_resume);exit;
                $updateData[] = $this->input->post('resume',TRUE);
                if(is_array($user_resume))
                    $user_resume = serialize(array_merge($updateData,$user_resume));
                else
                    $user_resume = serialize($updateData);
                //print_r($user_resume);exit;
                $value = array('resume'=>$user_resume);
                $this->user_model->updateUser($conditions,$value);
                $data = unserialize($user_resume);
                echo json_encode(array('status'=>'success','data' => $data));exit;
            }
        }else{
            $error = validation_errors();
            echo json_encode(array('status' => 'error','message' => $error));
        }
    }
    function deleteResume(){
    //load model
        $this->load->model('user_model');

        //load edit profile lang
        $this->lang->load('enduser/editProfile',$this->config->item('language_code'));
        $resume_post = $this->input->post('resume',TRUE);

        if($this->loggedInUser->id){
            $fields = array('users.resume');
            $conditions = array('users.id'=>$this->loggedInUser->id);
            $user_resume = $this->user_model->getUsers($conditions,$fields)->row_array();
            $user_resume = unserialize($user_resume['resume']);
            if(is_array($user_resume)){
                // nếu có resume và nó là một mảng
                $user_resume = array_diff($user_resume, array($resume_post));
                $user_resume = serialize($user_resume);
                $value = array('resume'=>$user_resume);
                $this->user_model->updateUser($conditions,$value);
                $data = unserialize($user_resume);
                echo json_encode(array('status'=>'success','data' => $data));exit;    
            }else{
                // nếu không có resume
                echo json_encode(array('status'=>'error','data' => serialize($user_resume)));exit;
            }            
        }else{
            echo json_encode(array('status' => 'error','message' => "loi roi"));
        }
    }

    function test(){
        //load model
        $this->load->model('user_model');

        //load edit profile lang
        $this->lang->load('enduser/editProfile',$this->config->item('language_code'));
        $resume_post = "fadsfasfsadfasf";

        if($this->loggedInUser->id){
            $fields = array('users.resume');
            $conditions = array('users.id'=>$this->loggedInUser->id);
            $user_resume = $this->user_model->getUsers($conditions,$fields)->row_array();
            $user_resume = unserialize($user_resume['resume']);
            if(is_array($user_resume)){
                // nếu có resume và nó là một mảng
                echo "<pre>";
                print_r($user_resume);
                echo "</pre>";
                $user_resume = array_diff($user_resume, array($resume_post));

                $user_resume = serialize($user_resume);
                $value = array('resume'=>$user_resume);
                $this->user_model->updateUser($conditions,$value);
                $data = unserialize($user_resume);
                echo json_encode(array('status'=>'success','data' => $data));exit;    
            }else{
                // nếu không có resume
            }
            echo json_encode(array('status' => 'error','message' => $this->input->post('resume')));
            
        }else{
            echo json_encode(array('status' => 'error','message' => "loi roi"));
        }
    }
    function editSkill(){
        if($this->input->post('data')){
            if($this->loggedInUser->id){
                $fields = array('user_categories.user_id','user_categories.user_categories');
                $condition = array('user_id'=>$this->loggedInUser->id);
                if($this->user_model->getUsers($condition,$fields)->num_rows() > 0){
                    $updateData['user_categories'] = $this->input->post('data',TRUE);
                    $this->user_model->updateCategories($condition,$updateData);
                    echo json_encode(array("status" => 'success','data' => $updateData['user_categories']));
                }else{
                    $updateData['user_categories'] = $this->input->post('data',TRUE);
                    $this->user_model->insertUserCategories($condition,$updateData);
                    echo json_encode(array("status" => 'success','data' => $updateData['user_categories']));
                }
            }
        }
        else{
            echo json_encode(array('status' => 'error'));
        }
    }
    function registerFacebook(){
        $this->load->library('facebook');
        $user = $this->facebook->getUser();

        if ($user) {
            try {
                $data = $this->facebook->api('/me');
                echo json_encode(array('status' => 'success','data' => $data));exit;
                //print_r($data['user_profile']);exit;
            } catch (FacebookApiException $e) {
                $user = null;
            }
        }else {
            $this->facebook->destroySession();
        }
        //$this->load->view('users/registerFacebook',$this->outputData);
    }

	function loginGoogle(){
		$this->load->library('googleplus');
    	
    	if (isset($_GET['code'])) 
    	{
    		$this->googleplus->access($_GET['code']);    		
    		$userGG = $this->googleplus->getInfoUser();
    		
			//$userGG = array_merge($userInfoGG, $profileGG);
			
    		if($userGG == null){
    			$authUrl = $this->googleplus->client->createAuthUrl();
				$result = array(
					'status' => "ERROR",
					'url' => $authUrl
				);
    		}else{
				$this->load->model('user_model');
				
				$user = $this->user_model->getUsers(array('email' => $userGG['emails'][0]['value']), array("email"));				
				
				$this->session->set_userdata('userGG', $userGG);
				
				if($user->num_rows > 0){				
					redirect('users/login');
				}else{
					redirect('buyer/signup');
				}				
			}
    	}elseif(isset($_GET['error'])){
    		redirect('users/login');
    	}else{
    		$authUrl = $this->googleplus->client->createAuthUrl();
			$result = array(
				'status' => "ERROR",
				'url' => $authUrl
			);
    	}      	
    	echo json_encode($result); die;
	}

	function ajaxLinkAcc()
    {
        //language file
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        //Load Models - for this function
        $this->load->model('user_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load cookie
        $this->load->helper('cookie');
        $this->load->helper('transaction');
        //Load Alert Helper
        $this->load->helper('alert');

        //Load Form Helper
        $this->load->helper('form');

        //Load Library File
        $this->load->library('encrypt');


        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
        //pr($_POST);
        //Get Form Data
        if ($this->input->post('linkAcc')) {
            //Set rules
            $this->form_validation->set_rules('password', 'lang:password_validation', 'required|ming_length[5]|trim|xss_clean');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));

            if ($this->form_validation->run()) {

                // Puhal Changes Removed the role Id from the conditions, inorder to remove the buyer and programmer radio button (Sep 17 Issue 4)
                $conditions = array('email' => $this->input->post('email'), 'password' => md5($this->input->post('password')), 'users.user_status' => '1');
                $query = $this->user_model->getUsers($conditions);


                if ($query->num_rows() > 0) {
                    $row = $query->row();
                    // update the last activity in the users table
                    $updateData = array();
                    $updateData['last_activity'] = get_est_time();

                    if($this->session->userdata('infoFacebook')){
                        $infoFacebook = $this->session->userdata('infoFacebook');

                        if(array_key_exists('id',$infoFacebook)) {
                            $insertFacebook['facebook_id'] = $infoFacebook['id'];
                            $insertFacebook['link'] = $infoFacebook['link'];
                            $insertFacebook['locale'] = $infoFacebook['locale'];
                            $insertFacebook['name'] = $infoFacebook['name'];
                            $insertFacebook['verified'] = $infoFacebook['verified'];
                            $time = time();
                            $insertFacebook['created'] = $time;
                            $insertFacebook['user_id'] = $row->id;
                            $this->user_model->addUserFacebook($insertFacebook);
                            $condition_fb = array('created' => $time);
                            $result = $this->user_model->getUserFacebook($condition_fb);
                            if($result->num_rows() > 0){
                                $facebook_id = $result->row()->id;
                            }
                        }
                        $this->session->unset_userdata('infoFacebook');
                    }
                    $updateData['facebook_id'] = $facebook_id;

                    if($row->logo == ""){
                        $filename = md5(time().rand()).".jpg";
                        @file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents("https://graph.facebook.com/{$insertFacebook['facebook_id']}/picture?type=large"));
                        $updateData['logo'] = $filename;
                        // cộng điểm kinh nghiệm
                        creditExperience($row->id,10);
                        // cộng điểm thưởng
                        creditBonus($row->id,5);
                    }


                    // update process for users table
                    $this->user_model->updateUser(array('id' => $row->id), $updateData);

                    //Check For Password
                    //if($this->input->post('pwd')==$this->common_model->getDecryptedString($row->password))
                    if (1) {
                        //Set Session For User
                        $this->auth_model->setUserSession($row);

						$result = array(
							'status' => 'COMPLETED',
							'message' =>  $this->lang->line('Login successful')
						);


                        if( ($this->input->post('id',TRUE) != 0) && (($row->role_id == 1)))
                           $result['url_redirect'] = 'project/create/'.$this->input->post('id',TRUE);
                        else{
                            $result['url_redirect'] = 'buyer/editProfileUpdate';
                        }


                        // check for private project user login
                    } else {

						$result = array(
							'status' => 'ERROR',
							'message' =>  $this->lang->line('Incorrect username or password')
						);
                        //Notification message
                        //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Incorrect username or password')));
                        //redirect('users/login');
                    }

                } else {

					$result = array(
						'status' => 'ERROR',
						'message' =>  $this->lang->line('Incorrect username or password')
					);
                    //Notification message
                    //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Incorrect username or password')));
                    //redirect('users/login');
                } //If username exists
            }
            //If End - Check For Validation
        } //If End - Check For Form Submission

		echo json_encode($result); die;

    }
    function ajaxLinkAccGoogle()
    {
        //language file
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        //Load Models - for this function
        $this->load->model('user_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load cookie
        $this->load->helper('cookie');

        //Load Alert Helper
        $this->load->helper('alert');

        //Load Form Helper
        $this->load->helper('form');

        //Load Library File
        $this->load->library('encrypt');


        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
        //pr($_POST);
        //Get Form Data
        if ($this->input->post('linkAcc')) {
            //Set rules
            $this->form_validation->set_rules('password', 'lang:password_validation', 'required|ming_length[5]|trim|xss_clean');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));

            if ($this->form_validation->run()) {

                // Puhal Changes Removed the role Id from the conditions, inorder to remove the buyer and programmer radio button (Sep 17 Issue 4)
                $conditions = array('email' => $this->input->post('email'), 'password' => md5($this->input->post('password')), 'users.user_status' => '1');
                $query = $this->user_model->getUsers($conditions);


                if ($query->num_rows() > 0) {
					$this->load->model('user_google_model');

                    $row = $query->row();
                    // update the last activity in the users table
                    $updateData = array();
                    $updateData['last_activity'] = get_est_time();

                    $infoGoogle = $this->session->userdata('infoGoogle');

                    if($infoGoogle != false){
                        $updateData['google_id'] = $infoGoogle['google_id'];

						$insertGoogle['google_id'] = $infoGoogle['google_id'];
                        $insertGoogle['display_name'] = $infoGoogle['display_name'];
                        $insertGoogle['gender'] = $infoGoogle['gender'];
                        $insertGoogle['avartar'] = $infoGoogle['avartar'];
                        $insertGoogle['birthday'] = $infoGoogle['birthday'];
                        $insertGoogle['created'] = time();
                        $insertGoogle['user_id'] = $row->id;

                        $this->user_google_model->addUserGoogle($insertGoogle);

                        $this->session->unset_userdata('infoGoogle');
                    }

                    if($row->logo == ""){
                        $filename = md5(rand()).".jpg";
                        @file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents($infoGoogle['avartar']));
                        $updateData['logo'] = $filename;
                    }


                    // update process for users table
                    $this->user_model->updateUser(array('id' => $row->id), $updateData);
                    //Check For Password
                    //if($this->input->post('pwd')==$this->common_model->getDecryptedString($row->password))
                    if (1) {
                        //Set Session For User
                        $this->auth_model->setUserSession($row);

                        $result = array(
                            'status' => 'COMPLETED',
                            'message' =>  $this->lang->line('Login successful')
                        );

                        $project_id = $this->uri->segment(3, 0);

                        if($project_id > 0){
                            if($row->role_id == 1){
                                $result['url_redirect'] = 'project/create/'.$project_id;
                            }elseif($row->role_id == 2){
                                $result['url_redirect'] = 'buyer/editProfileUpdate';
                            }
                        }else{
                            if($row->role_id == 1){
                                $result['url_redirect'] = 'buyer/viewMyProjects';
                            }elseif($row->role_id == 2){
                                $result['url_redirect'] = 'programmer/viewMyProjects';
                            }
                        }
                        if ($this->session->userdata('job_id') != '') {
                            $jobid = $this->session->userdata('job_id');
                            $this->session->unset_userdata('job');
                            $this->session->unset_userdata('view');
                            $this->session->unset_userdata('job_id');
                            redirect('project/view/' . $jobid);
                        }

                        // check for private project user login
                    } else {

                        $result = array(
                            'status' => 'ERROR',
                            'message' =>  $this->lang->line('Incorrect username or password')
                        );
                        //Notification message
                        //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Incorrect username or password')));
                        //redirect('users/login');
                    }

                } else {

                    $result = array(
                        'status' => 'ERROR',
                        'message' =>  $this->lang->line('Incorrect username or password')
                    );
                    //Notification message
                    //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Incorrect username or password')));
                    //redirect('users/login');
                } //If username exists
            }
            //If End - Check For Validation
        } //If End - Check For Form Submission

        echo json_encode($result); die;

    }
    function modalRegisterFacebook(){
        $this->load->helper('form');
        $this->load->helper('transaction');
        if($this->session->userdata('user_id'))
            redirect('home');
        //language file
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
//        //Get Form Data
//
       // if ($this->input->post('buyerConfirm')) { echo 123;exit;
            //Set rules
            $this->form_validation->set_rules('username', 'lang:buyer_name_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|callback__check_username|alpha_space|is_unique[users.user_name]');
            $this->form_validation->set_rules('password', 'lang:password', 'required|trim|min_length[5]|max_length[50]|xss_clean');
            $this->form_validation->set_rules('confirm-password', 'lang:password_confirm_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|matches[password]');
            $this->form_validation->set_rules('email', 'lang:email', 'required|trim|required|valid_email|min_length[5]|max_length[50]|xss_clean|callback__check_buyer_email|alpha_space|[users.email]');
            $this->form_validation->set_rules('role_id', "lang:I'm looking for", 'required');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
            $this->form_validation->set_message('max_length', '%s ' . $this->lang->line('max_length'));
            $this->form_validation->set_message('valid_email', '%s ' . $this->lang->line('valid_email'));
            $this->form_validation->set_message('matches', '%s ' . $this->lang->line('matches'));
            $this->form_validation->set_message('is_unique', '%s ' . $this->lang->line('is_unique'));


            if ($this->form_validation->run() == TRUE) {
//                if (check_form_token() === false) {
//                    redirect('home');
//                }

                $data = array();
                $data['user_name'] = $this->input->post('username', TRUE);
                $data['password'] = md5($this->input->post('password', TRUE));
                $data['email'] = $this->input->post('email', TRUE);
                $data['user_status'] = 1;
                $data['role_id'] = $this->input->post('role_id');

                if ($this->user_model->createUser($data) == TRUE) {
                    $condition = array('user_name' => $this->input->post('username', TRUE));
                    $query = $this->user_model->getUsers($condition);
                    if ($query->num_rows() > 0) {
                        $row = $query->row();

                        if($this->session->userdata('infoFacebook')){
                            $infoFacebook = $this->session->userdata('infoFacebook');

                            if(array_key_exists('id',$infoFacebook)) {
                                $insertFacebook['facebook_id'] = $infoFacebook['id'];
                                $insertFacebook['link'] = $infoFacebook['link'];
                                $insertFacebook['locale'] = $infoFacebook['locale'];
                                $insertFacebook['name'] = $infoFacebook['name'];
                                $insertFacebook['verified'] = $infoFacebook['verified'];
                                $time = time();
                                $insertFacebook['created'] = $time;
                                $insertFacebook['user_id'] = $row->id;
                                $this->user_model->addUserFacebook($insertFacebook);
                            }
                            $condition_fb = array('created' => $time);
                            $result = $this->user_model->getUserFacebook($condition_fb);
                            if($result->num_rows() > 0){
                                $facebook_id = $result->row()->id;
                            }
                            $updateData['facebook_id'] = $facebook_id;
                            //echo $this->config->item('basepath');exit;

                            $filename = md5(time().rand()).".jpg";
                            @file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents("https://graph.facebook.com/{$insertFacebook['facebook_id']}/picture?type=large"));
                            $updateData['logo'] = $filename;
                            $this->session->unset_userdata('infoFacebook');
                        }
                        $this->user_model->updateUser(array('id' => $row->id), $updateData);

                        // cộng điểm kinh nghiệm
                        creditExperience($row->id,20);
                        // cộng điểm thưởng
                        creditBonus($row->id,10);

                        if($query->num_rows() > 0){
                            //Set Session For User
                            $this->auth_model->setUserSession($row);

                            if(($this->uri->segment(3,'0')) && is_numeric($this->uri->segment(3,'0')) && $this->uri->segment(3,'0') != 0 && ($row->role_id == 1))
                                redirect('project/create/'.$this->uri->segment(3,'0'));
                            else{
                                redirect('buyer/editProfileUpdate');
                            }
                        }

                        redirect('users/login');
                    }
                    redirect('users/login');
                }


            } //Form Validation End
        $this->load->view('users/modal-register');
    }
	function modalRegisterGoogle(){
        $this->load->helper('form');
        $this->load->helper('transaction');
        if($this->session->userdata('user_id'))
            redirect('home');
        //language file
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
//        //Get Form Data
//
       // if ($this->input->post('buyerConfirm')) { echo 123;exit;
            //Set rules
            $this->form_validation->set_rules('username', 'lang:buyer_name_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|callback__check_username|alpha_space|is_unique[users.user_name]');
            $this->form_validation->set_rules('password', 'lang:password', 'required|trim|min_length[5]|max_length[50]|xss_clean');
            $this->form_validation->set_rules('confirm-password', 'lang:password_confirm_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|matches[password]');
            $this->form_validation->set_rules('email', 'lang:email', 'required|trim|required|valid_email|min_length[5]|max_length[50]|xss_clean|callback__check_buyer_email|alpha_space|[users.email]');
            $this->form_validation->set_rules('role_id', "lang:I'm looking for", 'required');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
            $this->form_validation->set_message('max_length', '%s ' . $this->lang->line('max_length'));
            $this->form_validation->set_message('valid_email', '%s ' . $this->lang->line('valid_email'));
            $this->form_validation->set_message('matches', '%s ' . $this->lang->line('matches'));
            $this->form_validation->set_message('is_unique', '%s ' . $this->lang->line('is_unique'));


            if ($this->form_validation->run() == TRUE) {
//                if (check_form_token() === false) {
//                    redirect('home');
//                }

//                if ($this->input->post('avatar-facebook', TRUE) != "") {
//                    //var_dump(url_download(,));
//                    $filename = $this->input->post('username', TRUE) . ".jpg";
//                    @file_put_contents($this->config->item('basepath') . "files/logos/" . $filename, file_get_contents($this->input->post('avatar-facebook', TRUE)));
//                } else {
//                    $filename = "";
//                }


                $data = array();
                $data['user_name'] = $this->input->post('username', TRUE);
                $data['password'] = md5($this->input->post('password', TRUE));
                $data['email'] = $this->input->post('email', TRUE);
                $data['user_status'] = 1;
                $data['role_id'] = $this->input->post('role_id');

                if ($this->user_model->createUser($data) == TRUE) {
					$this->load->model('user_google_model');

                    $condition = array('user_name' => $this->input->post('username', TRUE));
                    $query = $this->user_model->getUsers($condition);
                    if ($query->num_rows() > 0) {
                        $row = $query->row();

                        //$infoGoogle = $this->session->userdata('infoGoogle');
						$infoGoogle = $this->session->userdata('infoGoogle');
						if($infoGoogle != false){

							$insertGoogle['google_id'] = $infoGoogle['google_id'];
							$insertGoogle['display_name'] = $infoGoogle['display_name'];
							$insertGoogle['gender'] = $infoGoogle['gender'];
							$insertGoogle['avartar'] = $infoGoogle['avartar'];
							$insertGoogle['birthday'] = $infoGoogle['birthday'];
							$insertGoogle['created'] = time();
							$insertGoogle['user_id'] = $row->id;

							$this->user_google_model->addUserGoogle($insertGoogle);

                            $updateData['google_id'] = $infoGoogle['google_id'];
						}

						//echo $this->config->item('basepath');exit;

						//$filename = md5(time().rand()).".jpg";
						//@file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents("https://graph.facebook.com/{$insertFacebook['facebook_id']}/picture?type=large"));
						//$updateData['logo'] = $filename;
						$this->session->unset_userdata('infoGoogle');

						$filename = md5(rand()).".jpg";
						@file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents($insertGoogle['avartar']));
						$updateData['logo'] = $filename;
						$this->user_model->updateUser(array('id' => $row->id), $updateData);

                        // cộng điểm kinh nghiệm
                        creditExperience($row->id,20);
                        // cộng điểm thưởng
                        creditBonus($row->id,10);

                        if($query->num_rows() > 0){
                            //Set Session For User
                            $this->auth_model->setUserSession($row);

                            if(!empty($this->uri->segment(3,'0')) && is_numeric($this->uri->segment(3,'0')) && $this->uri->segment(3,'0') != 0 && ($row->role_id == 1))
                                redirect('project/create/'.$this->uri->segment(3,'0'));
                            else{
                                redirect('buyer/editProfileUpdate');
                            }
                            /*
                            if($row->role_id == 1){
                                redirect('project/create');
                            }else{
                                redirect('buyer/editProfileUpdate');
                            }
                            */
                        }

                        redirect('users/login');
                    }
                    redirect('users/login');
                }


            } //Form Validation End
        $this->load->view('users/modal-register');
    }
	function modalRegisterGoogle2(){
        $this->load->helper('form');
        $this->load->helper('transaction');
        if($this->session->userdata('user_id')){
            redirect('home');
		}

        //language file
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
//
       // if ($this->input->post('buyerConfirm')) { echo 123;exit;
            //Set rules
            $this->form_validation->set_rules('username', 'lang:buyer_name_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|callback__check_username|alpha_space|is_unique[users.user_name]');
            $this->form_validation->set_rules('password', 'lang:password', 'required|trim|min_length[5]|max_length[50]|xss_clean');
            $this->form_validation->set_rules('confirm-password', 'lang:password_confirm_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|matches[password]');
            $this->form_validation->set_rules('email', 'lang:email', 'required|trim|required|valid_email|min_length[5]|max_length[50]|xss_clean|callback__check_buyer_email|alpha_space|[users.email]');
            $this->form_validation->set_rules('role_id', "lang:I'm looking for", 'required');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
            $this->form_validation->set_message('max_length', '%s ' . $this->lang->line('max_length'));
            $this->form_validation->set_message('valid_email', '%s ' . $this->lang->line('valid_email'));
            $this->form_validation->set_message('matches', '%s ' . $this->lang->line('matches'));
            $this->form_validation->set_message('is_unique', '%s ' . $this->lang->line('is_unique'));


            if ($this->form_validation->run() == TRUE) {
//                if (check_form_token() === false) {
//                    redirect('home');
//                }

				$filename = '';
				ob_start();
				ob_end_clean();
				$infoGoogle = $this->session->userdata('infoGoogle');

                $data = array();
                $data['user_name'] = $this->input->post('username', TRUE);
                $data['password'] = md5($this->input->post('password', TRUE));
                $data['email'] = $this->input->post('email', TRUE);
                $data['user_status'] = 1;
                $data['role_id'] = $this->input->post('role_id');
                $data['logo'] = $filename;

                if ($this->user_model->createUser($data) == TRUE) {
					$this->load->model('user_google_model');
					
                    $condition = array('user_name' => $this->input->post('username', TRUE));
                    $fields = array('users.id');
                    $query = $this->user_model->getUsers($condition,$fields);
                    if ($query->num_rows() > 0) {
                        $row = $query->row();

                        if($infoGoogle !== FALSE){
                            $insertGoogle['google_id'] = $infoGoogle['id'];
                            $insertGoogle['display_name'] = $infoGoogle['displayName'];
                            $insertGoogle['gender'] = $infoGoogle['gender'];
                            $insertGoogle['avartar'] = $infoGoogle['image']['url'];
                            $insertGoogle['birthday'] = $infoGoogle['birthday'];
                            $insertGoogle['created'] = time();
                            $insertGoogle['user_id'] = $row->id;

                            $this->user_google_model->addUserGoogle($insertGoogle);

                            // cộng điểm kinh nghiệm
                            creditExperience($row->id,10);
                            // cộng điểm thưởng
                            creditBonus($row->id,5);

                            $this->session->unset_userdata('infoGoogle');
                        }
                       
                        // cộng điểm kinh nghiệm
                        creditExperience($row->id,20);
                        // cộng điểm thưởng
                        creditBonus($row->id,10);

                        if($query->num_rows() > 0){
                            //Set Session For User
                            $this->auth_model->setUserSession($row);

                            if($row->role_id == 1){
                                redirect('project/create');
                            }else{
                                redirect('buyer/editProfileUpdate');
                            }
                        }

                        redirect('users/login');
                    }
                    redirect('users/login');
                }

            } //Form Validation End
        $this->load->view('users/modal-register');
    }
    function notice(){
        $this->load->view('notice');
    }
    function moreDevRecommened(){
        //print_r($this->input->post('array_list'));exit;
        $this->load->helper('file');

        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));

        if($this->input->post('array_list',TRUE)) {
            if($this->loggedInUser->id) {
                $conditions_invite = array('project_invitation.project_id' => $this->input->post('project_id', TRUE), 'project_invitation.sender_id' => $this->loggedInUser->id);
                $fields_invite = array('project_invitation.receiver_id');
                $listUserInvite = $this->user_model->getProgrammerInvitation($conditions_invite, $fields_invite);

                $array = array();
                if ($listUserInvite->num_rows() > 0) {
                    foreach ($listUserInvite->result() as $item) {
                        $this->outputData['UserInvited'][] = $item->receiver_id;
                    }
                }


                $not_in = $this->input->post('array_list', TRUE);
                $conditions_user = array('users.user_status' => 1, 'users.role_id' => 2);
                $order_user = array('users.id', 'random');
                $limit_user = array('8');
                $userCate = $this->user_model->getUsersRandom($conditions_user, null, $limit_user, $order_user, $not_in);
                if ($userCate->num_rows() > 0) {
                    $this->outputData['userCate'] = $userCate->result();
                    $this->outputData['projectId'] = $this->input->post('project_id',TRUE);
                    //echo json_encode(array('status' => 'success','data' => $this->outputData['userCate']));exit;
                }
            }
        }
        $this->load->view('users/moreDevRecommened',$this->outputData);
    }

    function moreDevRecommenedInvite(){
        $this->load->helper('file');
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));
        if($this->input->post('array_list',TRUE)){
            if($this->loggedInUser->id){
                $id_other = $this->input->post('id_other',TRUE);
                $not_in = $this->input->post('array_list', TRUE);
                $user_categories_sample = $this->input->post('user_categories_sample', TRUE);
                $limit_user = array('4');
                $moreUser = $this->user_model->getUsersMoreInvite($user_categories_sample,$not_in,$id_other,$limit_user);
                if($moreUser->num_rows() > 0){
                    $this->outputData['moreUserInvite'] = $moreUser;
                }
            }
        }
        $this->load->view('project/moreDevRecommenedInvite',$this->outputData);
    }

    function addWatchList(){
        $user_id = $this->input->post('user_id',TRUE);

        if(isset($this->loggedInUser->id) == TRUE){
            if($this->loggedInUser->role_id == 1) {
                $insertData['user_id'] = $this->loggedInUser->id;
                $insertData['dev_id'] = $user_id;
                $insertData['created'] = time();

                $this->user_model->addWatchList($insertData);
                echo json_encode(array('status' => 'success'));
                exit;
            }
            else{
                echo json_encode(array('status' => 'not-client'));exit;
            }
        }else{
            echo json_encode(array('status' => 'not-login'));exit;
        }
    }
    function removeWatchList(){
        $user_id = $this->input->post('user_id',TRUE);

        if(isset($this->loggedInUser->id) == TRUE){
            if($this->loggedInUser->role_id == 1) {
                $conditions = array('user_watchlist.user_id' => $this->loggedInUser->id,'user_watchlist.dev_id' => $user_id);

                $this->user_model->removeWatchList($conditions);
                echo json_encode(array('status' => 'success'));
                exit;
            }
            else{
                echo json_encode(array('status' => 'not-client'));exit;
            }
        }else{
            echo json_encode(array('status' => 'not-login'));exit;
        }
    }
    function category(){
        $this->load->library('pagination');
        $this->load->helper('file');
        $this->load->helper('projectcases');
        $category = $this->uri->segment(3,'0');
        if($category){
            $condition_freelancer = array(
                "users.suspend_status"=>'0',
                "users.ban_status" => '0',
                "users.role_id" => 2 ,
            );
            if(isset($this->loggedInUser->id) == TRUE)
                $userId = $this->loggedInUser->id;
            else
                $userId = 0;

            $condition = array('categories.is_deleted' => 0);
            $fields = array('categories.id','categories.category_name');
            $listCategory = $this->skills_model->getCategory($condition,$fields);

            if($listCategory->num_rows() > 0){
                foreach($listCategory->result_array() as $item){
                    $this->outputData['listCategory'][$item['id']] = $item['category_name'];
                }
            }


            $conditions = array('groups.is_deleted' => 0);
            $fields = array('groups.group_name','groups.id','groups.parent_id');
            $listCategories = $this->skills_model->getGroup($conditions,$fields);

            // load contries
            $this->outputData['countries'] = $this->skills_model->getCountries(NULL, NULL, NULL, array('0' => 30));

            foreach($listCategories->result() as $item){
                if($item->parent_id == 0) {
                    $this->outputData['listParentCategories'][$item->id]['id'] = $item->id;
                    $this->outputData['listParentCategories'][$item->id]['name'] = $item->group_name;
                }
            }

            foreach($this->outputData['listParentCategories'] as $item){
                foreach($listCategories->result() as $item2){
                    if($item['id'] == $item2->parent_id){
                        $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['id'] = $item2->id;
                        $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['name'] = $item2->group_name;
                        $numUserCategories = $this->user_model->getCountCategorybyUser($item2->id);
                        if($numUserCategories->num_rows() > 0)
                            $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['num'] = $numUserCategories->num_rows();
                        else
                            $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['num'] = 0;
                    }
                }
            }


            $category = "(".$category.")";
            $fields = array('users.id');
            $this->outputData['countFreelancer'] = $this->user_model->getFreelancer($condition_freelancer,$userId,null,$category,$fields);

            $page_rows = $this->config->item('mail_limit');
            //pagination
            $config['base_url']     = site_url('users/category');
            $config['total_rows']   = $this->outputData['countFreelancer']->num_rows();
            $config['per_page'] = $page_rows;
            //$config['cur_page'] = $start;
            $this->pagination->initialize($config);
            $this->outputData['pagination']   = $this->pagination->create_links2();
            $this->outputData['listFreelancer'] = $this->user_model->getFreelancer($condition_freelancer, $userId, null, $category);

        }
        $this->load->view('users/category',$this->outputData);
    }

} //End  Users Class

/* End of file Users.php */
/* Location: ./app/controllers/Users.php */